package interceptcrossing.ui;

import interceptcrossing.Intercept;
import interceptcrossing.InterceptFileReader;
import interceptcrossing.InterceptFileWriter;
import interceptcrossing.Intersection;
import interceptcrossing.command.Command;
import interceptcrossing.command.CommandManager;
import interceptcrossing.ui.command.ImportInterceptsCommand;
import interceptcrossing.ui.command.RemoveAllInterceptsCommand;
import interceptcrossing.ui.command.RemoveInterceptCommand;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * Основное окно
 *
 * @author Igor Botyan
 */
public class MainWindow extends JFrame {

	private MainWindowDirector windowDirector;

	private JToolBar toolBar;
	private JButton importButton;
	private JButton exportButton;
	private JButton generateButton;
	private JButton addButton;
	private JButton removeButton;
	private JButton clearButton;
	private JButton findButton;
	private JButton aboutButton;
	private JButton exitButton;
	private JButton undoButton;
	private JButton redoButton;
	private JButton findByStepButton;

	private JMenuBar menuBar;
	private JMenuItem exitMenuItem;
	private JMenuItem importMenuItem;
	private JMenuItem exportMenuItem;
	private JMenuItem generateMenuItem;
	private JMenuItem addMenuItem;
	private JMenuItem removeMenuItem;
	private JMenuItem clearMenuItem;
	private JMenuItem findMenuItem;
	private JMenuItem aboutMenuItem;
	private JMenuItem undoMenuItem;
	private JMenuItem redoMenuItem;
	private JCheckBoxMenuItem selectMenuItem;
	private JCheckBoxMenuItem addManuallyMenuItem;
	private JMenuItem findByStepMenuItem;

	private JSplitPane workingSplitPane;
	private PaintPanel paintPanel;
	private InterceptPanel interceptPanel;
	private IntersectionPanel intersectionPanel;
	private JSplitPane infoSplitPane;

	public MainWindow() {
		super("Переcечение отрезков");

		super.setIconImage(new ImageIcon(
			MainWindow.class.getResource("window.png")).getImage());

		this.windowDirector = new MainWindowDirector(this);
		this.workingSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
		this.paintPanel = new PaintPanel(this.windowDirector);
		this.interceptPanel = new InterceptPanel(this.windowDirector);
		this.intersectionPanel = new IntersectionPanel(this.windowDirector);
		this.infoSplitPane = new JSplitPane();

		this.initMenuBar();
		this.initToolBar();
		this.initLayout();
		this.initActions();

		super.setMinimumSize(new Dimension(640, 480));
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		super.pack();
		super.setExtendedState(JFrame.MAXIMIZED_BOTH);
		super.setLocationRelativeTo(null);
	}

	private void initMenuBar() {
		this.menuBar = new JMenuBar();

		super.setJMenuBar(this.menuBar);

		JMenu fileMenu = new JMenu("Файл");

		this.importMenuItem = new JMenuItem("Загрузить...");
		this.exportMenuItem = new JMenuItem("Сохранить...");
		this.exitMenuItem = new JMenuItem("Выход");

		this.importMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("import.png")));
		this.exportMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("export.png")));
		this.exitMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("exit.png")));

		fileMenu.add(this.importMenuItem);
		fileMenu.add(this.exportMenuItem);
		fileMenu.addSeparator();
		fileMenu.add(this.exitMenuItem);

		JMenu editMenu = new JMenu("Правка");
		this.undoMenuItem = new JMenuItem("Отмена");
		this.undoMenuItem.setIcon(new ImageIcon(
			MainWindow.class.getResource("undo.png")));
		this.undoMenuItem.setEnabled(false);
		this.redoMenuItem = new JMenuItem("Повтор");
		this.redoMenuItem.setIcon(new ImageIcon(
			MainWindow.class.getResource("redo.png")));
		this.redoMenuItem.setEnabled(false);

		editMenu.add(this.undoMenuItem);
		editMenu.add(this.redoMenuItem);

		JMenu interceptMenu = new JMenu("Отрезок");
		this.addMenuItem = new JMenuItem("Добавить...");
		this.removeMenuItem = new JMenuItem("Удалить");
		this.clearMenuItem
			= new JMenuItem("Удалить все");
		this.generateMenuItem = new JMenuItem("Сгенерировать...");
		this.findMenuItem
			= new JMenuItem("Найти пересечения");
		this.findByStepMenuItem = new JMenuItem("Найти пересечения по шагам");

		this.addMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("add.png")));
		this.removeMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("remove.png")));
		this.clearMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("clear.png")));
		this.findMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("find.png")));
		this.generateMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("generate.png")));
		this.findByStepMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("find_by_step.png")));

		interceptMenu.add(this.addMenuItem);
		interceptMenu.add(this.removeMenuItem);
		interceptMenu.add(this.clearMenuItem);
		interceptMenu.add(this.generateMenuItem);
		interceptMenu.addSeparator();
		interceptMenu.add(this.findMenuItem);
		interceptMenu.add(this.findByStepMenuItem);

		JMenu modeMenu = new JMenu("Режим");
		this.selectMenuItem = new JCheckBoxMenuItem("Выделение");
		this.selectMenuItem.setSelected(true);
		this.selectMenuItem.setIcon(new ImageIcon(
			MainWindow.class.getResource("select.png")));
		this.addManuallyMenuItem = new JCheckBoxMenuItem("Добавление");
		this.addManuallyMenuItem.setSelected(false);
		this.addManuallyMenuItem.setEnabled(false);
		this.addManuallyMenuItem.setIcon(new ImageIcon(
			MainWindow.class.getResource("add_manually.png")));

		modeMenu.add(this.selectMenuItem);
		modeMenu.add(this.addManuallyMenuItem);

		JMenu helpMenu = new JMenu("?");
		this.aboutMenuItem = new JMenuItem("О программе...");

		this.aboutMenuItem.setIcon(
			new ImageIcon(MainWindow.class.getResource("about.png")));

		helpMenu.add(aboutMenuItem);

		this.menuBar.add(fileMenu);
		this.menuBar.add(editMenu);
		this.menuBar.add(interceptMenu);
		this.menuBar.add(modeMenu);
		this.menuBar.add(helpMenu);

		this.exportMenuItem.setEnabled(false);
		this.clearMenuItem.setEnabled(false);
		this.removeMenuItem.setEnabled(false);
		this.findMenuItem.setEnabled(false);
		this.findByStepMenuItem.setEnabled(false);
	}

	private void initToolBar() {
		this.toolBar = new JToolBar();
		this.toolBar.setFloatable(false);

		this.importButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("import.png")));
		this.importButton.setToolTipText("Загрузить отрезки");
		this.exportButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("export.png")));
		this.exportButton.setToolTipText("Сохранить отрезки");

		this.undoButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("undo.png")));
		this.undoButton.setToolTipText("Отмена");
		this.redoButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("redo.png")));
		this.redoButton.setToolTipText("Повтор");

		this.addButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("add.png")));
		this.addButton.setToolTipText("Добавить отрезок");
		this.removeButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("remove.png")));
		this.removeButton.setToolTipText("Удалить отрезок");
		this.clearButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("clear.png")));
		this.clearButton.setToolTipText("Удалить все отрезки");
		this.generateButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("generate.png")));
		this.generateButton.setToolTipText("Сгенерировать отрезки");
		this.findButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("find.png")));
		this.findButton.setToolTipText("Найти пересечения");
		this.findByStepButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("find_by_step.png")));
		this.findByStepButton.setToolTipText("Найти пересечения по шагам");

		this.aboutButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("about.png")));
		this.aboutButton.setToolTipText("О программе");

		this.exitButton = new JButton(
			new ImageIcon(MainWindow.class.getResource("exit.png")));
		this.exitButton.setToolTipText("Выход");

		this.toolBar.add(this.importButton);
		this.toolBar.add(this.exportButton);
		this.toolBar.addSeparator();
		this.toolBar.add(this.undoButton);
		this.toolBar.add(this.redoButton);
		this.toolBar.addSeparator();
		this.toolBar.add(this.addButton);
		this.toolBar.add(this.removeButton);
		this.toolBar.add(this.clearButton);
		this.toolBar.add(this.generateButton);
		this.toolBar.add(this.findButton);
		this.toolBar.add(this.findByStepButton);
		this.toolBar.addSeparator();
		this.toolBar.add(this.aboutButton);
		this.toolBar.addSeparator();
		this.toolBar.add(this.exitButton);

		this.undoButton.setEnabled(false);
		this.redoButton.setEnabled(false);
		this.clearButton.setEnabled(false);
		this.removeButton.setEnabled(false);
		this.findButton.setEnabled(false);
		this.findByStepButton.setEnabled(false);
		this.exportButton.setEnabled(false);
	}

	private void initLayout() {
		Container contentPane = super.getContentPane();
		contentPane.setLayout(new GridBagLayout());

		contentPane.add(this.toolBar, new GridBagConstraints(1, 1, 1, 1, 1.0,
			0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
			new Insets(2, 2, 2, 2), 0, 0));

		this.interceptPanel.setBorder(new TitledBorder("Отрезки"));
		this.intersectionPanel.setBorder(new TitledBorder("Пересечения отрезков"));

		this.infoSplitPane.setLeftComponent(this.interceptPanel);
		this.infoSplitPane.setRightComponent(this.intersectionPanel);

		this.workingSplitPane.setTopComponent(new JScrollPane(this.paintPanel));
		this.workingSplitPane.setBottomComponent(this.infoSplitPane);

		contentPane.add(this.workingSplitPane, new GridBagConstraints(1, 2, 1, 1, 1.0,
			1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
			new Insets(2, 2, 2, 2), 0, 0));
	}

	private void initActions() {
		this.windowDirector.addListener(new MainWindowDirector.Listener() {

			public void interceptAdded(Intercept intercept) {
			}

			public void interceptRemoved(Intercept intercept) {
			}

			public void interceptsCleared() {
			}

			public void intersectionsFound(Set<Intersection> intersections) {
				if (intersections.isEmpty()) {
					JOptionPane.showMessageDialog(MainWindow.this,
						"Пересечений не найдено.", "Уведомление",
						JOptionPane.INFORMATION_MESSAGE);
				}
			}

			public void currentInterceptChanged(int index, Intercept intercept) {
			}
		});

		this.importMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.importIntercepts();
			}
		});

		this.exportMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.exportIntercepts();
			}
		});

		this.addMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.addIntercept();
			}
		});

		this.removeMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.removeIntercept();
			}
		});

		this.clearMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.clearIntercepts();
			}
		});

		this.generateMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.generateIntercepts();
			}
		});

		this.findMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.findIntersections();
			}
		});

		this.exitMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.exit();
			}
		});

		this.aboutMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.about();
			}
		});

		this.importButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.importIntercepts();
			}
		});

		this.exportButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.exportIntercepts();
			}
		});

		this.addButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.addIntercept();
			}
		});

		this.removeButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.removeIntercept();
			}
		});

		this.clearButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.clearIntercepts();
			}
		});

		this.generateButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.generateIntercepts();
			}
		});

		this.findButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.findIntersections();
			}
		});

		this.exitButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.exit();
			}
		});

		this.aboutButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.about();
			}
		});

		this.undoMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				CommandManager cmdManager = windowDirector.getCommandManager();

				if (cmdManager.canUndo()) {
					cmdManager.undo();
				}
			}
		});

		this.redoMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				CommandManager cmdManager = windowDirector.getCommandManager();

				if (cmdManager.canRedo()) {
					cmdManager.redo();
				}
			}
		});

		this.undoButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				CommandManager cmdManager = windowDirector.getCommandManager();

				if (cmdManager.canUndo()) {
					cmdManager.undo();
				}
			}
		});

		this.redoButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				CommandManager cmdManager = windowDirector.getCommandManager();

				if (cmdManager.canRedo()) {
					cmdManager.redo();
				}
			}
		});

		this.findByStepMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				DebugWindow debugWindow = new DebugWindow(MainWindow.this,
					windowDirector);
				debugWindow.setVisible(true);
			}
		});

		this.findByStepButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				DebugWindow debugWindow = new DebugWindow(MainWindow.this,
					windowDirector);
				debugWindow.setVisible(true);
			}
		});

		this.addComponentListener(new ComponentAdapter() {

			@Override
			public void componentResized(ComponentEvent e) {
				int wpHeight = workingSplitPane.getSize().height;
				workingSplitPane.setDividerLocation((wpHeight * 0.75) / wpHeight);

				int infoWidth = infoSplitPane.getSize().width;
				infoSplitPane.setDividerLocation((infoWidth * 0.5) / infoWidth);
			}
		});

		this.windowDirector.addListener(new MainWindowDirector.ListenerAdapter() {

			@Override
			public void interceptAdded(Intercept intercept) {
				boolean moreThanOneIntercept
					= windowDirector.getIntercepts().size() > 1;
				findButton.setEnabled(moreThanOneIntercept);
				findMenuItem.setEnabled(moreThanOneIntercept);
				findByStepButton.setEnabled(moreThanOneIntercept);
				findByStepMenuItem.setEnabled(moreThanOneIntercept);

				exportButton.setEnabled(true);
				exportMenuItem.setEnabled(true);
				clearButton.setEnabled(true);
				clearMenuItem.setEnabled(true);
			}

			@Override
			public void interceptRemoved(Intercept intercept) {
				boolean hasIntercepts = windowDirector.getIntercepts().size() > 0;
				boolean moreThanOneIntercept
					= windowDirector.getIntercepts().size() > 1;

				findButton.setEnabled(moreThanOneIntercept);
				findMenuItem.setEnabled(moreThanOneIntercept);
				findByStepButton.setEnabled(moreThanOneIntercept);
				findByStepMenuItem.setEnabled(moreThanOneIntercept);

				exportButton.setEnabled(hasIntercepts);
				exportMenuItem.setEnabled(hasIntercepts);
				clearButton.setEnabled(hasIntercepts);
				clearMenuItem.setEnabled(hasIntercepts);
			}

			@Override
			public void interceptsCleared() {
				findButton.setEnabled(false);
				findMenuItem.setEnabled(false);
				findByStepButton.setEnabled(false);
				findByStepMenuItem.setEnabled(false);
				exportButton.setEnabled(false);
				exportMenuItem.setEnabled(false);
				clearButton.setEnabled(false);
				clearMenuItem.setEnabled(false);
			}

			@Override
			public void currentInterceptChanged(int index, Intercept intercept) {
				removeButton.setEnabled(index >= 0);
				removeMenuItem.setEnabled(index >= 0);
			}
		});

		this.selectMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				setSelectMode();
			}
		});

		this.addManuallyMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				setAddingMode();
			}
		});

		this.windowDirector.getCommandManager().addListener(new CommandManager.Listener() {

			public void commandDone(CommandManager cmdManager, Command command) {
				this.fireCommand(cmdManager);
			}

			public void commandUndone(CommandManager cmdManager, Command command) {
				this.fireCommand(cmdManager);
			}

			public void commandRedone(CommandManager cmdManager, Command command) {
				this.fireCommand(cmdManager);
			}

			private void fireCommand(CommandManager cmdManager) {

				boolean canRedo = cmdManager.canRedo();
				String redoToolTipText = canRedo ? "Повтор: "
					+ cmdManager.getNextCommand().getDescription() : "Повтор";

				redoButton.setEnabled(canRedo);
				redoMenuItem.setEnabled(canRedo);
				redoButton.setToolTipText(redoToolTipText);
				redoMenuItem.setToolTipText(redoToolTipText);

				boolean canUndo = cmdManager.canUndo();
				String undoToolTipText = canUndo ? "Отмена: "
					+ cmdManager.getPreviousCommand().getDescription() : "Отмена";

				undoButton.setEnabled(canUndo);
				undoMenuItem.setEnabled(canUndo);
				undoButton.setToolTipText(undoToolTipText);
				undoMenuItem.setToolTipText(undoToolTipText);
			}
		});

		this.findByStepButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.findIntersectionsByStep();
			}
		});

		this.findByStepMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				MainWindow.this.findIntersectionsByStep();
			}
		});

		this.windowDirector.addListener(new MainWindowDirector.Listener() {
			public void interceptAdded(Intercept intercept) {
				this.handle();
			}

			public void interceptRemoved(Intercept intercept) {
				this.handle();
			}

			public void interceptsCleared() {
				this.handle();
			}

			public void intersectionsFound(Set<Intersection> intersections) {
			}

			public void currentInterceptChanged(int index, Intercept intercept) {
			}

			private void handle() {
				boolean canFindIntersections = windowDirector.interceptsCount() >= 2;
				findButton.setEnabled(canFindIntersections);
				findMenuItem.setEnabled(canFindIntersections);
				findByStepButton.setEnabled(canFindIntersections);
				findByStepMenuItem.setEnabled(canFindIntersections);

				addManuallyMenuItem.setEnabled(windowDirector.hasIntercepts());
			}
		});
	}

	private void findIntersections() {
		if (this.windowDirector.getIntercepts().size() < 2) {
			JOptionPane.showMessageDialog(this, "Перед поиском пересечений " +
				"должно быть добавлено хотя бы 2 отрезка",
				"Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}

		this.windowDirector.findIntersections();
	}

	private void findIntersectionsByStep() {
		if (this.windowDirector.getIntercepts().size() < 2) {
			JOptionPane.showMessageDialog(this, "Перед поиском пересечений " +
				"по шагам должно быть добавлено хотя бы 2 отрезка",
				"Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}

		// TODO
	}

	private void setSelectMode() {
		this.addManuallyMenuItem.setSelected(false);
		this.selectMenuItem.setSelected(true);
		this.paintPanel.setMode(PaintPanel.Mode.SELECTING);
	}

	private void setAddingMode() {
		this.addManuallyMenuItem.setSelected(true);
		this.selectMenuItem.setSelected(false);
		this.paintPanel.setMode(PaintPanel.Mode.ADDING);
	}

	private void importIntercepts() {
		/*if (this.windowDirector.hasIntercepts()) {
			this.windowDirector.clearIntercepts();
		}*/

		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File("."));
		fileChooser.setMultiSelectionEnabled(false);

		int result = fileChooser.showOpenDialog(this);

		if (result == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();

			if (file == null) {
				return;
			}

			try {
				InterceptFileReader reader = new InterceptFileReader(file);

				/*this.windowDirector.getCommandManager().redo();
				this.windowDirector.clearIntercepts();*/
				windowDirector.getCommandManager().doCommand(
					new ImportInterceptsCommand(windowDirector, reader.readIntercepts()));

				/*for (Intercept intercept : reader.readIntercepts()) {
					if(this.windowDirector.has)
					this.windowDirector.addIntercept(intercept);
				}*/
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, e.getMessage(),
					"Ошибка", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				this.windowDirector.clearIntercepts();
			}
		}
	}

	private void exportIntercepts() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File("."));
		fileChooser.setMultiSelectionEnabled(false);

		int result = fileChooser.showSaveDialog(this);

		if (result == JFileChooser.APPROVE_OPTION) {
			InterceptFileWriter writer = null;

			try {
				writer = new InterceptFileWriter(fileChooser.getSelectedFile());

				for (Intercept intercept : this.windowDirector.getIntercepts()) {
					writer.write(intercept);
				}

				JOptionPane.showMessageDialog(this,
					"Отрезки успешно сохранены",
					"Уведомление", JOptionPane.INFORMATION_MESSAGE);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, e.getMessage(),
					"Ошибка", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			} finally {
				if (writer != null) {
					writer.close();
				}
			}
		}
	}

	private void exit() {
		System.exit(0);
	}

	private void clearIntercepts() {
		if (this.windowDirector.hasIntercepts()) {
			/*int result = JOptionPane.showConfirmDialog(this,
				"Вы уверены, что хотите удалить все отрезки?", "Подтверждение",
				JOptionPane.YES_NO_OPTION);

			if (result == JOptionPane.YES_OPTION) {*/
			this.windowDirector.getCommandManager().doCommand(
				new RemoveAllInterceptsCommand(this.windowDirector));
			//}
		}
	}

	private void generateIntercepts() {
		/*if (this.windowDirector.hasIntercepts()) {
			int result = JOptionPane.showConfirmDialog(this,
				"Перед генерацией новых отрезков старые будут удалены. " +
					"Продолжить?", "Подтверждение", JOptionPane.YES_NO_OPTION);

			if (result != JOptionPane.YES_OPTION) {
				return;
			}
		}*/

		GenerationDialog dialog = new GenerationDialog(this, this.windowDirector);
		dialog.setVisible(true);
	}

	private void addIntercept() {
		AddInterceptDialog dialog
			= new AddInterceptDialog(this, this.windowDirector);
		dialog.setVisible(true);
	}

	private void removeIntercept() {
		Intercept intercept = this.windowDirector.getCurrentIntercept();
		assert (intercept != null);

		/*int result = JOptionPane.showConfirmDialog(this,
			"Вы уверены, что хотите удалить отрезок?", "Подтверждение",
			JOptionPane.YES_NO_OPTION);

		if (result != JOptionPane.YES_OPTION) {
			return;
		}*/

		this.windowDirector.getCommandManager().doCommand(
			new RemoveInterceptCommand(this.windowDirector, intercept));
	}

	private void about() {
		JOptionPane.showMessageDialog(MainWindow.this,
			"Пересечение отрезков\n\nСПбГЭТУ \"ЛЭТИ\", 2010 г.\n" +
				"Ботян И., Воробьёва М., Королёв Ю., Овчаренко А.",
			"О программе", JOptionPane.INFORMATION_MESSAGE);
	}
}
